<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="消息提示的文案"
        type="info"
        center
        show-icon></el-alert>
      <el-steps :active='activeIndex - 0' align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addForm" :rules="addForm_rules" ref="addForm_ref"  label-position='top' class="demo-ruleForm">
        <el-tabs tab-position='left' v-model='activeIndex' :before-leave='beforeLeave' @tab-click='tabClick'>
          <el-tab-pane label="基本参数" name='0'>
            <el-form-item label='商品名称' prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type='number'></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type='number'></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"  type='number'></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="options"
                :props="props"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name='1'>
            <el-form-item :label='i.attr_name' v-for='i in manyList' :key='i.attr_id'>
              <el-checkbox-group v-model='i.attr_vals'>
                <el-checkbox class='checkbox' border :label="j" v-for='(j,index) in i.attr_vals' :key='index' ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name='2'>
            <el-form-item :label='i.attr_name' v-for='(i,j) in onlyList' :key='j'>
              <el-input v-model='i.attr_vals'></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name='3'>
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :headers='token'
              list-type="picture"
              :on-success='uploadsuccess'>
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name='4'>
            <textarea style='width:99%' cols="30" rows="10"></textarea>
            <el-button style='margin-top:20px' type="primary" @click='addGoods'>添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog
      title="图片预览"
      :visible.sync="pictureDialog"
      width="50%">
      <img :src='pictureUrl'>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex:0,
      addForm: {
        goods_name:'',
        goods_price:0,
        goods_number:0,
        goods_weight:0,
        goods_cat:'',
        goods_introduce:'',
        pics:[],
        attrs:[],
      },
      addForm_rules: {
        goods_name:[
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price:[
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_number:[
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_weight:[
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_cat:[
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
      },
      options:[],
      props:{
        expandTrigger: 'hover',
        children:'children',
        label:'cat_name',
        value:'cat_id'
      },
      manyList:[],
      onlyList:[],
      fileList:[],
      token:{Authorization:window.sessionStorage.getItem('token')},
      pictureUrl:'',
      pictureDialog:false,
    }
  },
  computed: {
    selectID() {
      if( this.addForm.goods_cat.length === 3 ) return this.addForm.goods_cat[2]
      return null
    }
  },
  methods: {
    async getCategories() {
      let res = await this.axios.get('categories')
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.options = res.data
    },
    handleChange() {
      if( this.addForm.goods_cat.length !== 3 ) return this.addForm.goods_cat = []
    },
    beforeLeave(active, old){
      if( old === '0' && this.addForm.goods_cat.length !== 3) {
        this.pop.error('请选择商品分类')
        return false
      }
    },
    tabClick( ) {  // 选项选中
      if( this.activeIndex === '1' ) {
        this.getAttrMany()
      } else if( this.activeIndex === '2' ) {
        this.getAttrOnly()
      }
    },
    async getAttrMany() {
      let res = await this.axios.get(`categories/${ this.addForm.goods_cat[2] }/attributes`, { params:{ sel:'many'}})
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      res.data.forEach( item => {
        item.attr_vals = item.attr_vals.split(',')
      })
      this.manyList = res.data
    },
    async getAttrOnly() {
      let res = await this.axios.get(`categories/${ this.addForm.goods_cat[2] }/attributes`, { params:{ sel:'only'}})
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.onlyList = res.data
    },
    handlePreview( file ) {
      this.pictureUrl = file.response.data.url
      this.pictureDialog = true
    },
    handleRemove(file) { // 将图片从表单数据内移除
      let pic = { pic : file.response.tmp_path }
      let index = this.addForm.pics.findIndex( item => item === pic )
      this.addForm.pics.splice(index, 1)
    },
    uploadsuccess( response ) {  // 上传成功后记录临时路径到提交的表单内
      let pic = { pic : response.data.tmp_path }
      this.addForm.pics.push( pic )
    },
    async addGoods() {
      let rel = await this.$refs.addForm_ref.validate().catch( err=>err)
      if( !rel ) return this.pop.error('请填写完整')
      let copy = {...this.addForm}
      copy.goods_cat = copy.goods_cat.join(',')
      this.manyList.forEach( item => {
        let i = {
          attr_id:item.attr_id,
          attr_value:item.attr_vals.join(',')
        }
        copy.attrs.push( i )
      })
      this.onlyList.forEach( item => {
        let i = {
          attr_id:item.attr_id,
          attr_value:item.attr_vals
        }
        copy.attrs.push( i )
      })
      let res = await this.axios.post('/goods', copy)
      if( res.meta.status !== 201 ) return this.pop.error(res.meta.msg)
      this.pop.success( res.meta.msg )
      this.$router.push('/goods')
    }
  },
  created() {
    this.getCategories()
  }
}
</script>

<style scoped>
.el-steps {
  margin-top:15px;
}
.el-tabs {
  height:100%;
  margin-top:20px;
}
.el-form {
  height:100%;
}
.checkbox {
  margin:0 10px 0 0 !important;
}
img {
  width:100%;
  height: 100%;
}
</style>